package com.atguigu.common.jwt;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author CaiLu
 * @date 2023/3/11
 * @apiNote
 */
public class JwtHelper {
    //JWT固定写法

    //令牌过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    //签名  根据签名来进行加密和解密
    private static String tokenSignKey = "123456";

    public static String createToken(Long userId, String username) {
        //根据用户名称和密码生成一个唯一的字符串
        String token = Jwts.builder()
                //JWT头
                .setSubject("AUTH-USER")
                //设置有效时长 当前时间 + 过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //设置它的有效载荷
                .claim("userId", userId)
                .claim("username", username)
                //签名哈希
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    //从token中获取用户id
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;
            //通过签名来解除生成字符串的加密
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
